import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export const useUserStore = defineStore('user', () => {
  // 状态
  const userInfo = ref<any>(null)
  const token = ref<string>('')

  // 计算属性
  const isLoggedIn = computed(() => !!token.value && !!userInfo.value)
  const avatar = computed(() => userInfo.value?.avatar || '')
  const username = computed(() => userInfo.value?.username || '')
  const _id = computed(() => userInfo.value?._id || '')

  // 退出登录
  const logout = () => {
    token.value = ''
    userInfo.value = null
    localStorage.removeItem('token')
    localStorage.removeItem('userInfo')
    sessionStorage.removeItem('token')
    sessionStorage.removeItem('userInfo')
  }

  // 设置 token（并持久化）
  const setToken = (val: string) => {
    token.value = val || ''
    try {
      localStorage.setItem('token', token.value)
      sessionStorage.setItem('token', token.value)
    } catch {}
  }

  // 设置用户信息（并持久化）
  const setUserInfo = (info: any) => {
    userInfo.value = info || null
    try {
      localStorage.setItem('userInfo', JSON.stringify(userInfo.value || {}))
      sessionStorage.setItem('userInfo', JSON.stringify(userInfo.value || {}))
    } catch {}
  }

  // 初始化（从持久化读取）
  try {
    const savedToken = localStorage.getItem('token') || sessionStorage.getItem('token')
    const savedUser = localStorage.getItem('userInfo') || sessionStorage.getItem('userInfo')
    if (savedToken) token.value = savedToken
    if (savedUser) userInfo.value = JSON.parse(savedUser)
  } catch {}

  return {
    // 状态
    userInfo,
    token,
    
    // 计算属性
    isLoggedIn,
    avatar,
    username,
    _id,
    
    // 方法
    logout,
    setToken,
    setUserInfo
  }
})
